    //
//  ShowTicketsViewController.m
//  AirTicket
//
//  Created by imac.bmw on 10-12-28.
//  Copyright 2010 aircococ. All rights reserved.
//

#import "ShowTicketsViewController.h"
#import "ShowTicketCell.h"
#import <QuartzCore/QuartzCore.h>

@implementation ShowTicketsViewController
@synthesize table;
@synthesize Result;
@synthesize dataArray;
@synthesize org,dest;
@synthesize cityDic;
@synthesize date;
@synthesize airwayCode;
@synthesize navTitle;
@synthesize dateLabel;
@synthesize waiting;
@synthesize waitingView;
@synthesize activity;
@synthesize headDatestring;


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	
	
	//nav的标题，而且关系到是否执行返程查询
	if ([[SaveDefaults valueForKey:@"singleOrDouble"] isEqualToString:@"往返"]) {
		self.navigationItem.title = self.navTitle;
	}
	else {
		self.navigationItem.title = @"选择航班";
	}
	
	UIImageView *background = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
	background.image = [UIImage imageNamed:@"ticketback.png"];
	[self.view addSubview:background];
	[background release];

			 	
	UITableView *aTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 26, 320, 352)
													  style:UITableViewStylePlain];
	self.table = aTable;
	[aTable release];
	self.table.delegate = self;
	self.table.dataSource = self;
	self.table.backgroundColor = [UIColor clearColor];
	table.separatorColor = [UIColor clearColor];
	[self.view addSubview:table];
	
	
	//
	UIImage *img = [UIImage imageNamed:@"showhead.png"];
	UIImageView *content = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, img.size.width, img.size.height)];
	content.image = img;
	[self.view addSubview:content];
	[content release];
	
	UIImage *image1 = [UIImage imageNamed:@"showfoot.png"];
	UIImageView *foot = [[UIImageView alloc]initWithFrame:CGRectMake(0, 378, image1.size.width, image1.size.height)];
	foot.image = image1;
	[self.view addSubview:foot];
	[foot release];
	
	//头顶概要
	headInfo = [[UILabel alloc]initWithFrame:CGRectMake(85, 4, 300, 15)];
	headInfo.text = [NSString stringWithFormat:@"/%@-%@ 共搜索到%d个航班",org,dest,[Result.ticketsArray count]];
	headInfo.font = [UIFont systemFontOfSize:13];
	headInfo.textColor = [UIColor whiteColor];
	headInfo.backgroundColor = [UIColor clearColor];
	[self.view addSubview:headInfo];
	
	
	UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(13, 4, 300, 15)];
	self.dateLabel = label;
	[label release];
	dateLabel.text = [NSString stringWithFormat:@"%@",[date convertDate]];
	dateLabel.font = [UIFont systemFontOfSize:13];
	dateLabel.textColor = [UIColor whiteColor];
	dateLabel.backgroundColor = [UIColor clearColor];
	[self.view addSubview:dateLabel];
	
		
	NSMutableArray *array = [[NSMutableArray alloc]init];
	self.dataArray = array;
	[array release];
	
	//加入下一天查询的按钮
	UIButton *next = [[UIButton alloc]initWithFrame:CGRectMake(260, 377, 60, 39)];
	[next setTag:100];
	[next setBackgroundImage:[UIImage imageNamed:@"houyitian.png"] forState:UIControlStateNormal];
	[next addTarget:self action:@selector(GetNextDay) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:next];
	[next release];
	
	//加入前一天查询的按钮
	UIButton *prev = [[UIButton alloc]initWithFrame:CGRectMake(0, 377, 60, 39)];
	[prev setTag:200];
	[prev setBackgroundImage:[UIImage imageNamed:@"qianyitian.png"] forState:UIControlStateNormal];
	[prev addTarget:self action:@selector(GetPrevDay) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:prev];
	[prev release];
	
	[self performSelectorInBackground:@selector(getCellData) withObject:nil];
}

-(void)GetNextDay {
	UIButton *next = (UIButton *)[self.view viewWithTag:100];
	next.enabled = NO;

	NSString *myDateString = [NSString stringWithFormat:@"%@",self.dateLabel.text];
	NSDateFormatter *inputFormat = [[NSDateFormatter alloc] init];
	[inputFormat setDateFormat:@"yyyy-MM-dd"]; 
	NSDate *theDate  = [inputFormat dateFromString:myDateString];
	theDate = [[NSDate alloc] initWithTimeInterval:24*3600 sinceDate:theDate];
	NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
	[outputFormat setDateFormat:@"yyyy-MM-dd"];
	
	self.headDatestring = [outputFormat stringFromDate:theDate];
	
	//如果是往返程航班
	NSString *flightKind = [SaveDefaults valueForKey:@"singleOrDouble"];
	NSString *backDate = [SaveDefaults valueForKey:@"backDate"];
	backDate = [backDate convertDate];
	NSLog(@"date = %@,backdate = %@",self.headDatestring,backDate);
	
	if ([flightKind isEqualToString:@"往返"] && [self.headDatestring isEqualToString:backDate]) {
		
			UIAlertView *alert = [[UIAlertView alloc]
								  initWithTitle:nil message:@"去程航班不能晚于返程航班" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
			[alert show];
			[alert release];
		next.enabled = YES;
	}
	else {
	QueryFlight *query = [[QueryFlight alloc] init];
	
	if ([self.navigationItem.title isEqualToString:@"选择去程航班"] || [self.navigationItem.title isEqualToString:@"选择航班"]) { //去程时点击列表
		query.orig = [SaveDefaults valueForKey:@"orgcode"];
		query.dest = [SaveDefaults valueForKey:@"dstcode"];
		
	}
	else {
		
		query.orig = [SaveDefaults valueForKey:@"dstcode"];
		query.dest = [SaveDefaults valueForKey:@"orgcode"];
	}
	
	query.delegate = self;
	query.flightDate = self.headDatestring;
	query.airway = [SaveDefaults objectForKey:@"airwayCode"];
	[query getTicketInfo];
	[query release];
	
	[self addWatingView];
	
	[SaveDefaults setBool:YES forKey:@"fromButton"];
	}
	[outputFormat release];
	[inputFormat release];
	[theDate release];

}



-(void)addWatingView {

	UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 60, 100, 20)];
	self.waiting = label;
	[label release];
	waiting.backgroundColor = [UIColor clearColor];
	waiting.text = @"正在查询...";
	waiting.textColor = [UIColor whiteColor];
	
	UIView *aWaitingView = [[UIView alloc]initWithFrame:CGRectMake(110, 150, 110, 90)];
	self.waitingView = aWaitingView;
	[aWaitingView release];
	waitingView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.77];
	waitingView.alpha = 0.8f;
	waitingView.layer.masksToBounds = YES;
	waitingView.layer.cornerRadius = 7;
	
	UIActivityIndicatorView * Activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
	self.activity = Activity;
	[Activity release];
	activity.frame = CGRectMake(45, 35, 20, 20);
	[waitingView addSubview:activity];
	[activity startAnimating];
	[waitingView addSubview:waiting];
	[self.view addSubview:waitingView];
}

-(void)GetPrevDay {
	UIButton *prev = (UIButton *)[self.view viewWithTag:200];
	prev.enabled = NO;
	
	NSString *myDateString = [NSString stringWithFormat:@"%@",self.dateLabel.text];
	NSDateFormatter *inputFormat = [[NSDateFormatter alloc] init];
	[inputFormat setDateFormat:@"yyyy-MM-dd"]; //2010-12-08 06:53:43
	
	//将NSString转换为NSDate
	NSDate *theDate  = [inputFormat dateFromString:myDateString];
	theDate = [[NSDate alloc] initWithTimeInterval:-24*3600 sinceDate:theDate];
	//设置新的日期格式
	NSDateFormatter *outputFormat = [[NSDateFormatter alloc] init];
	[outputFormat setDateFormat:@"yyyy-MM-dd"];

	self.headDatestring = [outputFormat stringFromDate:theDate];
	
	//如果是往返程航班
	NSString *flightKind = [SaveDefaults valueForKey:@"singleOrDouble"];
	NSString *goDate = [SaveDefaults valueForKey:@"goDate"];
	goDate = [goDate convertDate];
	NSLog(@"date = %@,godate = %@",self.headDatestring,goDate);
	
	if ([flightKind isEqualToString:@"往返"] && [self.headDatestring isEqualToString:goDate]) {
		
		UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle:nil message:@"返程航班不能早于去程航班" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil];
		[alert show];
		[alert release];
		prev.enabled = YES;
	}
	else {

	QueryFlight *query = [[QueryFlight alloc] init];
	
	if ([self.navigationItem.title isEqualToString:@"选择去程航班"] || [self.navigationItem.title isEqualToString:@"选择航班"]) { //去程时点击列表
		query.orig = [SaveDefaults valueForKey:@"orgcode"];
		query.dest = [SaveDefaults valueForKey:@"dstcode"];
		
	}
	else {
		
		query.orig = [SaveDefaults valueForKey:@"dstcode"];
		query.dest = [SaveDefaults valueForKey:@"orgcode"];
	}
	
	query.delegate = self;
	query.flightDate = self.headDatestring;
	query.airway = [SaveDefaults objectForKey:@"airwayCode"];
	[query getTicketInfo];
	[query release];
	
	[self addWatingView];
	
	[SaveDefaults setBool:YES forKey:@"fromButton"];
	
	}
	
	[inputFormat release];
	[outputFormat release];
	[theDate release];
}

//分解解析数据成单个的机票信息
-(void)getCellData { 
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	

	//-----------
//	if ([self.Result.ticketsArray count] == 0) {
//		UILabel *emptyMsg = [[UILabel alloc]initWithFrame:CGRectMake(15, 150, 290, 100)];
//		[emptyMsg setTag:300];
//		emptyMsg.text = @"很抱歉，没有搜寻到需要的航班";
//		emptyMsg.font = [UIFont systemFontOfSize:20];
//		[self.view addSubview:emptyMsg];
//		[emptyMsg release];
//	}
//	else {
//		UILabel *emptyMsg = (UILabel *)[self.view viewWithTag:300];
//		emptyMsg.alpha = 0;
//	}


	NSArray *ticketArray = [Result.ticketsArray retain];
	
	for (int i=0; i<[ticketArray count]; i++) {
		

		Tickets *aTicket = [[ticketArray objectAtIndex:i] retain];
		
		NSMutableArray *classArray = [aTicket.classArray retain];
	
		for (airClass *classInfo in classArray) {
			
			CellNeedData *cellData = [[CellNeedData alloc]init];
			
			cellData.date = Result.date;
			cellData.flightNum = aTicket.fltno;
			cellData.airways = aTicket.airways;
			cellData.org = aTicket.org;
			cellData.dst = aTicket.dst;
			cellData.deptime = aTicket.deptime;
			cellData.arrtime = aTicket.arrtime;
			cellData.planesty = aTicket.planesty;
			cellData.tax = aTicket.tax;
			cellData.fuel = aTicket.fuel;
			cellData.meal = aTicket.meal;
			cellData.price = classInfo.price;
			cellData.classtype = classInfo.classtype;
			cellData.cabin = classInfo.cabin;
			cellData.ticketsCount = classInfo.ticketsCount;
			cellData.discount = classInfo.discount;
			
			[self.dataArray addObject:cellData];
			
			[cellData release];
		}
		[aTicket release];
	}
	
	[self.table performSelectorOnMainThread: @selector(reloadData) withObject: nil waitUntilDone: NO];//最后一个参数？

	[pool drain];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

	return 59;
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

	return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    ShowTicketCell *cell = (ShowTicketCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ShowTicketCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	//-----------
	
	
	if (indexPath.row %2) {
		
		cell.backPic.image = [UIImage imageNamed:@"ticketcell.png"];
	}
	
	else {
		cell.backPic.image = [UIImage imageNamed:@"ticketcelldark.png"];

	}
	
	//------------------------
	CellNeedData *data = [self.dataArray objectAtIndex:indexPath.row];
    cell.fltno.text = data.flightNum;
	cell.classtype.text = [NSString stringWithFormat:@"%@ %@",data.classtype, data.cabin];
	cell.org.text = [data.org convertCitycode];
	cell.dst.text = [data.dst convertCitycode];
	cell.strtime.text = data.deptime;
	cell.arrtime.text = data.arrtime;
	
	if ([data.discount floatValue] >= 10.0) {

		cell.priceAndCount.text = [NSString stringWithFormat:@"全价 ￥ %@",data.price];
	}
	else {
		cell.priceAndCount.text = [NSString stringWithFormat:@"%@折 ￥ %@",data.discount,data.price];
	}
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	NSString *needQuery = [SaveDefaults valueForKey:@"singleOrDouble"];
	
	CellNeedData *aData = [[self.dataArray objectAtIndex:indexPath.row] retain];

	if ([needQuery isEqualToString:@"单程"]) { //单程航班
		[infoMgr saveData:aData forKey:@"单程航班"];
		OrderViewController *order = [[OrderViewController alloc]init];
		[self.navigationController pushViewController:order animated:YES];
		[order release];
		
	}
	else { //往返的航班
		
		if ([self.navigationItem.title isEqualToString:@"选择去程航班"]) { //去程时点击列表
			[infoMgr saveData:aData forKey:@"去程航班"];
			QueryFlight *query = [[QueryFlight alloc] init];
			query.orig = [SaveDefaults valueForKey:@"dstcode"];
			query.dest = [SaveDefaults valueForKey:@"orgcode"];
			query.delegate = self;
			query.flightDate = [SaveDefaults valueForKey:@"backDate"];
			query.airway = self.airwayCode;
			[query getTicketInfo];
			[query release];
			[SaveDefaults setBool:NO forKey:@"fromButton"];
			[self addWatingView];
			
		}
		else { //返程时点击列表
			[infoMgr saveData:aData forKey:@"返程航班"];
			OrderViewController *order = [[OrderViewController alloc]init];
			
			
			order.data = aData;
			
			[self.navigationController pushViewController:order animated:YES];
			[order release];
		}


	}
	[aData release];

}

-(void)didGetResluts:(QueryResults *)result {
	[activity stopAnimating];
	[waitingView removeFromSuperview];
	

	UIButton *next = (UIButton *)[self.view viewWithTag:100];
	next.enabled = YES;
	UIButton *prev = (UIButton *)[self.view viewWithTag:200];
	prev.enabled = YES;

	QueryResults *aResult = [result retain];
	
	
	BOOL fromWho = [SaveDefaults boolForKey:@"fromButton"];
	
	if (!fromWho) {
		ShowTicketsViewController *showTicket = [[ShowTicketsViewController alloc]init];
		showTicket.Result = aResult;
		showTicket.date = [SaveDefaults valueForKey:@"backDate"];
		showTicket.org = [SaveDefaults valueForKey:@"dst"];
		showTicket.dest = [SaveDefaults valueForKey:@"org"];
		showTicket.navTitle = @"选择返程航班";
		[self.navigationController pushViewController:showTicket animated:YES];
		[showTicket release];
	}
	else {
		dateLabel.text = [NSString stringWithFormat:@"%@",self.headDatestring];
		
		[self.dataArray removeAllObjects];
		self.Result = aResult;
		[self performSelectorInBackground:@selector(getCellData) withObject:nil];
		headInfo.text = [NSString stringWithFormat:@"/%@-%@ 共搜索到%d个航班",org,dest,[Result.ticketsArray count]];

	}

	
	[aResult release];
	
}
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[headInfo release];
	[headDatestring release];
	[activity release];
	[waiting release];
	[waitingView release];
	[dateLabel release];
	[navTitle release];
	[Result release];
	[cityDic release];
	[table release];
	//[result release];
    [super dealloc];
}
@end

